<template>
	<div class="upload-container">
		<n-button
			:style="{ background: color, borderColor: color }"
			size="small"
			type="primary"
			@click="state.dialogVisible = true"
		>
			{{ $t("tinymce.upimg.uploadBtn") }}
			<template #icon>
				<i class="el-icon-upload"></i>
			</template>
		</n-button>
		<n-modal
			v-model:show="state.dialogVisible"
			class="upload-modal"
			preset="dialog"
			:show-icon="false"
			:negative-text="$t('tinymce.upimg.cancel')"
			:positive-text="$t('tinymce.upimg.upload')"
			@positive-click="handlePositiveClick"
		>
			<template #header>
				<span class="modal-title">{{ $t("tinymce.upimg.title") }}</span>
			</template>
			<n-upload
				ref="uploadRef"
				:action="action"
				:data="data"
				:name="name"
				:headers="headers"
				accept=".jpg,.png,.jpeg,.webp,.gif,.JPG,.PNG,.JPEG,.WEBP"
				:default-upload="false"
				:show-file-list="true"
				:multiple="multiple"
				@before-upload="beforeUpload"
				@finish="uploadFinish"
			>
				<n-upload-dragger>
					<div style="margin-bottom: 12px">
						<n-icon size="48" :depth="3">
							<CloudUploadOutline />
						</n-icon>
					</div>
					<n-text style="font-size: 16px">{{ $t("tinymce.upimg.uploadText") }}</n-text>
				</n-upload-dragger>
			</n-upload>
		</n-modal>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import CloudUploadOutline from "@vicons/ionicons5/CloudUploadOutline";

interface EditorImage {
	fileNum: number;
	dialogVisible: boolean;
	fileList: any[];
}

withDefaults(
	defineProps<{
		color?: string;
		action: string;
		data?: object;
		name?: string;
		multiple?: boolean;
		headers?: object;
	}>(),
	{
		color: "#1890ff",
		data: () => ({}),
		name: "file",
		multiple: true,
		headers: () => ({}),
	},
);

const emit = defineEmits<{
	(event: "successCBK", value: any[]): void;
}>();

const uploadRef = ref();

const state = reactive<EditorImage>({
	fileNum: 0,
	dialogVisible: false,
	fileList: [],
});

function handlePositiveClick() {
	uploadRef.value.submit();
}

function uploadFinish({ file, event }: any) {
	file.response = JSON.parse(event.target.response);
	state.fileList.push(file);
	if (state.fileList.length === state.fileNum) {
		emit("successCBK", state.fileList);
		state.fileNum = 0;
		state.fileList = [];
	}
}

function beforeUpload({ file }: any) {
	if (
		![
			"image/jpg",
			"image/png",
			"image/jpeg",
			"image/webp",
			"image/gif",
			"image/JPG",
			"image/PNG",
			"image/JPEG",
			"image/WEBP",
		].includes(file.file.type)
	) {
		window.$message.error("只能上传图片，请重新上传");
		return false;
	}
	state.fileNum++;
	return true;
}
</script>

<style lang="scss" scoped>
.modal-title {
	font-size: 16px;
}
.upload-box {
	width: 400px;
	height: 300px;
}
.uploadBtn {
	margin-left: 10px;
}
</style>

<style lang="scss">
.upload-modal {
	width: 550px !important;
}
</style>
